package indi.zhifa.expshare.class001.chemicalmatch.util.openai.embding;

import indi.zhifa.expshare.class001.chemicalmatch.properties.OpenAiProperties;
import indi.zhifa.expshare.class001.chemicalmatch.util.openai.embding.entity.EmbeddingRequest;
import indi.zhifa.engine.core.common.entity.web.RestResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RequiredArgsConstructor
@Component
public class OpenAiEmbedUtil {
    private final OpenAiProperties mOpenAiProperties;
    private final RestTemplate mRestTemplate;

    public List<List<Float>> getEmbedding(List<String> pText) {
        String url = mOpenAiProperties.getApiUrl();
        EmbeddingRequest embeddingRequest = new EmbeddingRequest();
        embeddingRequest.initWithText(pText);
        HttpHeaders headers = new HttpHeaders();

        ParameterizedTypeReference<RestResponse<List<List<Float>>>> responseType = new ParameterizedTypeReference<RestResponse<List<List<Float>>>>() {};
        HttpEntity<EmbeddingRequest> requestEntity = new HttpEntity<>(embeddingRequest, headers);

        ResponseEntity<RestResponse<List<List<Float>>>> response = mRestTemplate.exchange(url, HttpMethod.POST, requestEntity,  responseType);


        if(response.getStatusCode().is2xxSuccessful()){
            return response.getBody().getData();
        }
        return null;


        /*WebClient webClient = WebClient.builder()
                .baseUrl(url)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer "+mOpenAiProperties.getSecKey())
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();

        EmbeddingResponse result = webClient.post().bodyValue(embeddingRequest)
                .retrieve()
                .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(),
                        resp -> resp.bodyToMono(String.class)
                        .flatMap(body -> Mono.error(new ServiceException(
                                "OpenAI 返回错误: ", body)))
                )
                .bodyToMono(EmbeddingResponse.class)
                .block(mOpenAiProperties.getTimeOut());
        return result.getVector();*/
    }


}
